// src/main/java/com/example/capsule/controller/InvitationPageController.java
package com.example.capsule.controller;

import com.example.capsule.service.InvitationService;
import com.example.capsule.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Optional;

@Controller
public class InvitationPageController {

    private final InvitationService invitationService;
    private final UserService userService;

    public InvitationPageController(InvitationService invitationService, UserService userService) {
        this.invitationService = invitationService;
        this.userService = userService;
    }

    @GetMapping("/invitation")
    public String showInvitationPage(@RequestParam String token,
                                     Model model,
                                     HttpServletRequest request) {

        // 1. 检查用户是否已登录
        boolean isLoggedIn = false;
        String userPhone = null;

        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            try {
                String jwtToken = authHeader.substring(7);
                isLoggedIn = userService.validateToken(jwtToken);
                if (isLoggedIn) {
                    userPhone = userService.getPhoneFromToken(jwtToken);
                }
            } catch (Exception e) {
                // token无效
                isLoggedIn = false;
            }
        }

        // 2. 获取邀请详细信息
        Optional<com.example.capsule.entity.Invitation> invitationOpt =
                invitationService.getInvitationByToken(token);

        if (invitationOpt.isEmpty()) {
            model.addAttribute("error", "邀请链接已失效");
            return "invitation-page";
        }

        com.example.capsule.entity.Invitation invitation = invitationOpt.get();

        // 3. 添加模型属性
        model.addAttribute("token", token);
        model.addAttribute("isLoggedIn", isLoggedIn);
        model.addAttribute("userPhone", userPhone);
        model.addAttribute("intendedRecipient", invitation.getRecipientPhone());
        model.addAttribute("senderPhone", "未知"); // 需要从胶囊获取
        model.addAttribute("capsuleTitle", "时光胶囊"); // 需要从胶囊获取

        // 4. 记录访问日志
        System.out.println("邀请页面访问 - Token: " + token +
                ", 已登录: " + isLoggedIn +
                ", 用户: " + userPhone +
                ", 目标接收人: " + invitation.getRecipientPhone());

        return "invitation-page";
    }
}